package com.butterfly.hotkey.dashboard.framework.config;

import com.butterfly.hotkey.common.exception.CommonException;
import com.butterfly.hotkey.common.result.Result;
import com.butterfly.hotkey.core.constant.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 统一异常处理类<br>
 * 捕获程序所有异常，针对不同异常，采取不同的处理方式
 *
 * @author butterfly
 */
@RestControllerAdvice
public class ExceptionHandleAdvice {

    private static final Logger log = LoggerFactory.getLogger(Constants.CLIENT);

    /**
     * 其他异常
     */
    @ExceptionHandler({Exception.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<Object> handleException(HttpServletRequest request, Exception e) {
        log.error("Server Exception:", e);
        return Result.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "系统异常");
    }

    /**
     * 自定义异常
     */
    @ExceptionHandler({CommonException.class})
    public Result<Object> handleCommonException(CommonException e, HttpServletResponse response) {
        return Result.error(e);
    }

    /**
     * 校验异常
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        List<ObjectError> errors = e.getBindingResult().getAllErrors();
        StringBuilder errorMessage = new StringBuilder();
        for (ObjectError error : errors) {
            errorMessage.append(error.getDefaultMessage()).append("\n");
        }
        return Result.error(HttpStatus.BAD_REQUEST.value(), errorMessage.substring(0, errorMessage.length() - 1));
    }

}
